//
//  PartPayVc.swift
//  TianTianBiTing
//
//  Created by Gox mac 2 on 2019/1/2.
//  Copyright © 2019 Gox_WallyDiao. All rights reserved.
//

import UIKit

class PartPayVc: TTBaseVC {
    var programId:Int = 0
    
    var newPrice:NSNumber = 0
    var startPoint:Int = 1
    var on_off:Bool = false
    var allChoose:Bool = false
    var partHeight:CGFloat = 0.0
    let PartPayCellID = "PartPayCell"
    
    var seasionsArr:[Int] = [Int]()
    var playListModelArr:[PlayListModel] = [PlayListModel]()
    
    lazy var leftBtn:UIButton = {
        let button = UIButton(type: UIButton.ButtonType.custom)
        button.frame = FRAME_CGFloat(105,16.5, 16, 12)
        button.setImage(IMAGE(name: "icon_kai"), for: .normal)
        button.addTarget(self, action: #selector(btnAction(btn:)), for: .touchUpInside)
        button.tag = 11
        return button
    }()
    
    lazy var rightBtn:UIButton = {
        let button = UIButton(type: UIButton.ButtonType.custom)
        button.frame = FRAME_CGFloat(SCREEN_WIDTH  - 82, 8.5, 72.5, 28.5)
        button.setTitle("全选本页", for: .normal)
        button.addTarget(self, action: #selector(btnAction(btn:)), for: .touchUpInside)
        button.setTitleColor(RGB(230, 67, 64), for: .normal)
        button.titleLabel?.font = FONT(13)
        button.layer.borderWidth = 1
        button.layer.borderColor = RGB(230, 67, 64).cgColor
        button.layer.cornerRadius = 3
        button.tag = 12
        return button
    }()
    
    lazy var centreLabel:UILabel = {
        let label = UILabel.init(frame: FRAME_CGFloat(SCREEN_WIDTH / 2 - 50, 13, 100, 18.5))
        label.text = ""
        label.font = FONT(13)
        label.textColor = RGB(230, 67, 64)
        label.textAlignment = .center
        return label
        
    }()
    
    lazy var leftLabel:UILabel = {
        let label = UILabel.init(frame: FRAME_CGFloat(15, 13, 100, 18.5))
        label.font = FONT(13)
        label.text = "选集(1-50)"
        label.textColor = RGB(230, 67, 64)
        label.textAlignment = .left
        return label
        
    }()
    
    lazy var tableView: UITableView = {
        let tableView = TTTableView.init(frame: FRAME_CGFloat(0, 44, SCREEN_WIDTH, SCREEN_HEIGHT - OFFSET_TOP - 44 - 54), style: UITableView.Style.plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.white
        tableView.bounces = true
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.register(NIBNAME(PartPayCellID), forCellReuseIdentifier: PartPayCellID)
        tableView.tableFooterView = UIView.init(frame: .zero)
        return tableView
    }()
    
    lazy var headView:UIView = {
        let view = UIView.init()
        view.backgroundColor = WhiteBackColor
        return view
    }()
    
    lazy var bcView:UIView! = {
        let bcView = UIView()
        return bcView
    }()
    
    deinit {
        if self.bcView != nil {
            self.bcView.removeFromSuperview()
            self.bcView = nil
        }
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setTopView()
        setUI()
        setBottomView()
        setTableData()
        setCollectData()
        self.navigationItem.title = "批量购买"
    }

    func setUI() {
        self.view.addSubview(self.tableView)
        self.tableView.tableHeaderView = headView
    }
    
    func setTopView() {
        let topView = UIView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, 44))
        topView.backgroundColor = RGB(251, 222, 221)
        self.view.addSubview(topView)
        topView.addSubview(leftLabel)
        topView.addSubview(leftBtn)
        topView.addSubview(centreLabel)
        topView.addSubview(rightBtn)
    }
    
    func setBottomView() {
        let bottom = PartPayBottomView.init(frame: FRAME_CGFloat(0, SCREEN_HEIGHT - OFFSET_BOTTOM - 54, SCREEN_WIDTH, 54))
        bottom.delegate = self
        self.view.addSubview(bottom)
    }
    
    func setCollectData() {
        HomeRequestModel.loadBatchSeasonsData(parameters: ["programId":programId]) { (success, message, model) in
            if success && model != nil {
                self.partHeight = self.countToHeight(count: model?.area.count ?? 0)
                let part = PartCollectView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, self.partHeight), height: self.partHeight)
                part.modelList = model
                part.delegate = self
                self.centreLabel.text = "共\(model?.totalSeason ?? 0)集"
                self.headView.addSubview(part)
                self.headView.frame = .zero
                self.headView.isHidden = true
            } else {
                TTAlertView.showMessage(message: message)
            }
        }
    }
    
    func setTableData() {
        HomeRequestModel.loadPlayListData(programId: programId, parameters: ["userId":String.getUserId(),"startPoint":self.startPoint,"maxPage":50]) { (success, message, model, page) in
            if success && model != nil {
                self.playListModelArr = model!
                
                self.tableView.reloadData()
            } else {
                TTAlertView.showMessage(message: message)
            }
        }
    }
    
    func countToHeight(count:Int) -> CGFloat {
        let height = (count / 4 + 1) * 37
        return CGFloat(height)
    }
    
    @objc func btnAction(btn: UIButton) {
        if btn.tag == 11{
            if on_off {
                self.headView.frame = .zero
                self.headView.isHidden = true
                leftBtn.setImage(IMAGE(name: "icon_kai"), for: .normal)
            } else {
                self.headView.frame = FRAME_CGFloat(0, 0, SCREEN_WIDTH, self.partHeight)
                self.headView.isHidden = false
                leftBtn.setImage(IMAGE(name: "icon_shou"), for: .normal)
            }
            on_off = !on_off
            self.tableView.reloadData()
        } else if btn.tag == 12 {
            if allChoose {
                self.rightBtn.setTitle("全选本页", for: .normal)
                self.seasionsArr.removeAll()
            } else {
                self.rightBtn.setTitle("取消全选", for: .normal)
                for model in self.playListModelArr {
                    self.seasionsArr = seasionsArr + [model.id]
                }
            }
            allChoose = !allChoose
            self.tableView.reloadData()
        }
        
    }
    
    func confirmPurchase() {
        var str = ""
        for s in seasionsArr {
            str = str + "\(s),"
        }
        HomeRequestModel.buyPartSeason(parameters: ["userId":String.getUserId(),"programId":programId,"seasonIds":str]) { (success, message, state) in
            if success {
                TTAlertView.showMessage(message: message)
                TTNotificationCenter.Post(RefreshPlayVcData, obj: nil)
            } else {
                if state == "2" {
                    TTAlertView.ask(title: nil, question: message, leftTitle: "取消", rightTitle: "充值", okBlock: {
                        let wal = WalletVc()
                        PUSHVIEWCONTROLLER(wal)
                    }, noBlock: {
                        
                    })
                } else {
                    TTAlertView.showMessage(message: message)
                }
            }
        }
    }
    
    func createPayOrderView() {
        let bView = PayOrderDetailsView.init(frame: UIScreen.main.bounds)
        bView.delegate = self
        bView.setData(imageStr: self.playListModelArr[0].imageUrl ?? "", albumStr: self.playListModelArr[0].title ?? "", numberStr: "\(seasionsArr.count)集", priceStr: "\(String.money(newPrice) ?? "0")听币")
        self.bcView = bView
        UIApplication.shared.keyWindow?.addSubview(self.bcView)
        
    }
}

// MARK: *******  协议  ********
extension PartPayVc: UITableViewDelegate,UITableViewDataSource, PartPayBottomViewDelegate, PartCollectViewDelegate, PayOrderDetailsViewDelegate {
    func payOrderDetailsViewAction(tag: Int) {
        if tag == 31 {
            //            self.closePayOrderView()
        } else if tag == 32 {
            self.confirmPurchase()
        } else {
            
        }
        self.bcView.removeFromSuperview()
    }
    
    func BuyRightBtnAction(tag: Int) {
        if tag == 11 {
//            HomeRequestModel.buyAllSeason(parameters: ["userId":String.getUserId(),"programId":programId,"balance":TTAudioPlayer.totalCount as Any]) { (success, message) in
//                TTAlertView.showMessage(message: message)
//            }
            TTAlertView.showMessage(message: "暂不支持全集购买！")
        } else if tag == 12 {
            self.createPayOrderView()
        }
        
    }
    
    func PartCollectViewClick(index: Int, str: String) {
        self.leftLabel.text = "选集(\(str))"
        self.startPoint = index + 1
        self.setTableData()
        self.headView.frame = .zero
        self.headView.isHidden = true
        leftBtn.setImage(IMAGE(name: "icon_kai"), for: .normal)
        on_off = false
        self.rightBtn.setTitle("全选本页", for: .normal)
        self.seasionsArr.removeAll()
        allChoose = false
    }
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
   
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.playListModelArr.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: PartPayCellID) as! PartPayCell
        cell.titleLabel.text = "\(self.playListModelArr[indexPath.row].title ?? "--") " + "第\(self.playListModelArr[indexPath.row].season ?? "--")章 " + "\(self.playListModelArr[indexPath.row].describe ?? "--")"
        if allChoose {
            cell.chooseImage?.image = IMAGE(name: "icon_choose1")
        } else {
            if seasionsArr.contains(self.playListModelArr[indexPath.row].id) {
                cell.chooseImage?.image = IMAGE(name: "icon_choose1")
            } else {
                cell.chooseImage?.image = IMAGE(name: "icon_noChoose1")
            }
            
        }
//        cell.modelList = self.listModelArr[indexPath.row]
        cell.selectionStyle = .none
        self.tableView.allowsSelection = true
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     
        if seasionsArr.contains(self.playListModelArr[indexPath.row].id) {
            seasionsArr = seasionsArr.filter{$0 != self.playListModelArr[indexPath.row].id}
            newPrice = String.subtractMoney(money1: newPrice, money2: self.playListModelArr[indexPath.row].price ?? 0) ?? 0
        } else {
            seasionsArr = seasionsArr + [self.playListModelArr[indexPath.row].id]
            newPrice = String.addMoney(money1: newPrice, money2: self.playListModelArr[indexPath.row].price ?? 0) ?? 0
        }

        self.tableView.reloadData()
    }
    
}
